#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2017/12/22 下午5:00
# @Auther   : tonybearpan

import os
import re
import requests
import zipfile


def chrome_spider():
    r = requests.get("http://www.nruan.com/soft/network/browser/").text
    for link in re.findall(r'<a\b[^>]+\bhref="([^"]*)"[^>]*>([\s\S]*?)</a>', r):
        if ("Chrome" in link[1] or "chrome" in link[1]) and "/>" not in link[1]:
            version = str(re.findall(r'Chrome \d*', link[1])[0][-2:])
            if version not in local_versions():
                download_chrome(link[0], version)
                download_driver("https://npm.taobao.org/mirrors/chromedriver", version)
                break


def local_versions():
    cs = os.listdir("driver")
    vs = list()
    for c in cs:
        vs.append(c[:2])
    return vs


def download_chrome(url, version):
    html = requests.get(url).text.encode("utf-8")
    hs = html.split("无更新")
    for h in hs:
        if len(h) < 10000 and "64位" in h:
            for link in re.findall(r'<a\b[^>]+\bhref="([^"]*)"[^>]*>([\s\S]*?)</a>', h):
                if "google.com" in link[0] and "/>" not in link[1]:
                    download(link[0], "chrome/{v}.exe".format(v=version))


def download(url, path):
    with open(path, "wb") as code:
        code.write(requests.get(url).content)


def download_driver(d_url, cv):
    drivers = re.findall(r'<a\b[^>]+\bhref="([^"]*)"[^>]*>([\s\S]*?)</a>', requests.get(d_url).text)
    version = "0.0"
    for i in range(len(drivers)):
        driver = drivers[i]
        if "/mirrors/chromedriver/" in driver[0] and "i" not in driver[1] and "_" not in driver[1]:
            nv = version_compare(version, drivers[i][1][:-1])
            # print version, drivers[i][1][:-1], "=>", nv
            version = nv
    url = "https://npm.taobao.org/mirrors/chromedriver/{version}/chromedriver_win32.zip".format(version=version)
    zip_file = "driver/driver.zip"
    download(url, zip_file)
    zf = zipfile.ZipFile(zip_file, 'r')
    for z_file in zf.namelist():
        zf.extract(z_file, "driver/")
    os.remove(zip_file)
    os.renames("driver/chromedriver.exe", "driver/{v}.exe".format(v=cv))


def version_compare(v1, v2):
    v1_list = v1.split(".")
    v2_list = v2.split(".")
    for i in range(len(v1_list)):
        if int(v1_list[i]) > int(v2_list[i]):
            return v1
        if int(v1_list[i]) < int(v2_list[i]):
            return v2
    return v1


chrome_spider()
